package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.domain.dto.OrderPayDto;
import com.hmall.domain.pojo.*;
import com.hmall.domain.utils.SnowFlakeUtil;
import com.hmall.domain.utils.ThreadLocalUtil;
import com.hmall.feign.common.AddressFeignClient;
import com.hmall.feign.common.ItemFeignClient;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.OrderDetailService;
import com.hmall.order.service.OrderLogisticsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单业务层接口实现类
 *
 * @author xiaojiangshi
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderDetailService detailService;

    @Autowired
    private OrderLogisticsService logisticsService;

    @Autowired
    private ItemFeignClient itemFeignClient;

    @Autowired
    private AddressFeignClient addressFeignClient;


    /**
     * 根据条件提交订单
     *
     * @param orderPayDto 订单信息
     * @return 订单id
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Long commitOrder(OrderPayDto orderPayDto) {
        SnowFlakeUtil flakeUtil = new SnowFlakeUtil(1, 1);
        long nextId = flakeUtil.nextId();
        Item item = itemFeignClient.findById(orderPayDto.getItemId());
        Long userId = Long.valueOf(ThreadLocalUtil.getId());

        //封装order对象
        Order order = new Order();
        Long price = item.getPrice();
        Long totalFee = price * orderPayDto.getNum();
        order.setTotalFee(totalFee);
        order.setStatus(1);
        order.setId(nextId);
        order.setUserId(userId);
        //把订单保存到tb_order表中
        this.save(order);

        //封装orderDetail对象
        OrderDetail detail = new OrderDetail();
        BeanUtils.copyProperties(item, detail, "id");
        detail.setOrderId(nextId);
        detail.setNum(orderPayDto.getNum());
        detail.setTitle(item.getName());
        detail.setItemId(item.getId());
        //把订单详情对下昂保存到tb_order_detail表中
        detailService.save(detail);

        Address address = addressFeignClient.findAddressById(orderPayDto.getAddressId());
        OrderLogistics logistics = new OrderLogistics();
        BeanUtils.copyProperties(address, logistics);
        logistics.setOrderId(nextId);
        logisticsService.save(logistics);

        itemFeignClient.reduceIvo(orderPayDto.getItemId(), orderPayDto.getNum(), null);


        return nextId;
    }
}
